<template>
  <div class="text-gray-500 apps-container h-full">
    <div class="p-1">
      <div class="flex justify-end px-3 mb-2">
        <div class="cursor-pointer" @click="handleCommand('logout')">
          <vui-icon icon="logout-circle-r-line" />
        </div>
      </div>
      <div v-if="showPage" class="px-3 pb-3">
        <div class="flex flex-wrap pt-[120px]">
          <div
            v-for="(v, index) in getApps"
            :key="index"
            class="app-item w-full bg-white rounded-lg sahdow-lg overflow-hidden flex justify-center items-center cursor-pointer"
          >
            <div class="text-center item-text">
              <div class="uppercase text-xl text-gray-700 mb-2">{{ v.ORG_NAME }}</div>
              <div class="text-base text-gray-700 mb-2 font-semibold">{{ v.APP_CODE_ALIAS }}</div>
              <div class="text-gray-500 text-xs p-1 mb-2 rounded">{{ v.APP_NAME }}</div>
              <div class="inter-btn flex items-center justify-center" @click="toReq(v)">
                <span>{{ translateTitle('Base.apps.进入') }}</span>
                <vui-icon icon="arrow-right-circle-line" />
              </div>
            </div>
            <img alt="" class="item-img" src="../assets/wms_images/appItemImg.png" />
          </div>
        </div>
        <VuiModal v-show="showCommonModal" v-model="showCommonModal">
          <template #title>{{ item.APP_NAME }}</template>
          <div class="layer-modal-body overflow-auto w-[800px] h-[480px]">
            <!-- <div class="mb-[30px] ml-[80px] mr-[40px]">
              <el-input v-model.trim="wmsSearchKey" class="input-with-select" placeholder="请输入" @change="wmsSearch">
                <template #prepend>
                  <el-select v-model="searchType">
                    <el-option v-for="t in searchOptions" :key="t.value" :label="t.label" :value="t.value" />
                  </el-select>
                </template>
                <template #append>
                  <el-button @click="wmsSearch">
                    <vui-icon icon="search-line" />
                    搜索
                  </el-button>
                </template>
              </el-input>
            </div> -->
            <div v-for="(items, i) in selectList" :key="i">
              <div class="flex">
                <p v-if="items.SELECT_NAME" class="w-[120px] leading-[36px] font-semibold">{{ items.SELECT_NAME }}:</p>
                <div class="w-[calc(100% - 120px)]">
                  <el-select
                    v-model="items[items.SELECT_CODE]"
                    clearable
                    :disabled="!items.APP_SELECTS_VALUE || items.APP_SELECTS_VALUE.length == 0"
                    filterable
                    :placeholder="translateTitle('Base.apps.请选择')"
                    @change="orgChang(items, i)"
                  >
                    <el-option v-for="(v, itIndex) in items.APP_SELECTS_VALUE" :key="itIndex" :label="v.NAME" :value="v[items.SELECT_CODE]" />
                  </el-select>
                </div>
              </div>
              <div class="border-b border-gray-400 border-1 border-dashed mb-8 mt-6"></div>
            </div>
            <div class="flex justify-center p-3 mt-8">
              <el-button v-if="selectList.length > 0" class="commitBtn" :loading="toBtnLoading" type="primary" @click="toWms">
                <vui-icon icon="checkbox-circle-line" />
                {{ translateTitle('Base.apps.确认') }}
              </el-button>
            </div>
          </div>
        </VuiModal>
      </div>
    </div>
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import { translateTitle } from '@/utils/i18n'
  import { getUserInfo, queryByOrgId, judgeToken, getSelectResource } from '@commonProject/api/user'
  export default defineComponent({
    name: 'AppsPage',
    data() {
      return {
        showCommonModal: false,
        showPage: false,
        item: {},
        form: {
          ORG_LIST: [],
          ORG_NAME: '',
          ORG_ID: '',
          WAREHOUSES: [],
          WAREHOUSE_ID: '',
        },
        ORG_LIST: [], // 搜索后的列表
        WAREHOUSES: [], // 搜索后的列表
        toBtnLoading: false,
        searchType: '',
        whModalOrgListExpand: false,
        selectList: [],
        remainingData: [],
        superior: 0,
        clickSort: 0,
        appCode: '',
      }
    },
    computed: {
      //获取选择模块信息
      getApps() {
        return this.$store.getters['user/apps']
      },
      getAppId() {
        return this.$store.getters['user/appId']
      },
      getLanguage() {
        return this.$store.getters['user/language']
      },
    },
    mounted() {
      console.log(this.getApps)
      judgeToken().then((res) => {
        if (!res.data.pass) {
          //过期
          this.$store.dispatch('user/logout')
        }
        console.log('res', res)
      })
    },
    async created() {
      let _appid = this.$route.query['appid']
      let _back = this.$route.query['back']
      let _token = this.$route.query['tk']
      let language = this.$route.query['language'] || 'zh_CN'
      if (_appid) {
        this.showPage = true
        // let app = this.getApps.find((item) => item.ID == _appid)
        // console.log('跳转到', app)
        // this.toIndex(app)
      } else {
        // 只有一个的时候直接跳转
        // if (this.getApps.length <= 1) {
        //   this.showPage = false
        //   this.toIndex(this.getApps[0])
        // } else {
        //   this.showPage = true
        // }
        this.showPage = true
      }

      if (_back === 'true') {
        // console.log('设置token=========', window.location.href)
        this.$store.dispatch('user/setToken', _token)
        this.$store.dispatch('user/setLanguage', language)
        console.log(await this.getToApps(_appid, this.$route.query['appCode'], language))
        let apps = await this.getToApps(_appid, this.$route.query['appCode'], language)
        console.log('apps======', apps.app)
        this.$store.dispatch('user/setApps', apps.app)
        this.autoShowModal(_appid)
      }
    },
    methods: {
      async getToApps(appId, appCode, language) {
        const { data } = await getUserInfo({
          appId: appId,
          appCode: appCode,
          language: language,
        })
        return data
      },
      translateTitle,
      //自动打开弹框
      autoShowModal(appid) {
        let appInfo = this.getApps.find((v) => v.ID === appid)
        console.log('_back', appInfo)
        this.toReq(appInfo)
      },
      async queryByOrgId(id) {
        //queryByorgIdAndUserId
        const { data } = await queryByOrgId(id)
        let list = data['wms.warehouse.queryByorgIdAndUserId'].data
        // console.log(list)
        this.form.WAREHOUSES = list
        // 触发查询
      },
      async toReq(item) {
        this.item = item
        this.appCode = item.APP_CODE
        this.showCommonModal = true
        let data = await this.getSelectResource()
        let data1
        console.log(JSON.parse(JSON.stringify(data)))
        for (let index = 0; index < data.length; index++) {
          if (index !== 0) {
            let obj = data[index - 1].APP_SELECTS_VALUE.find((el) => el[data[index - 1].SELECT_CODE] == data[index - 1][data[index - 1].SELECT_CODE])
            data1 = await this.getSelectResource({ ...obj, NEXT_SORT: data[index].SORT })
            data[index] = data1
          }
          console.log(data[index])
          if (data[index]?.APP_SELECTS_VALUE.length === 0) {
            return this.$baseMessage(`请授权${data[index].SELECT_NAME.slice(-2)}`, 'error')
          } else {
            data[index][data[index].SELECT_CODE] = data[index].APP_SELECTS_VALUE[0][data[index].SELECT_CODE]
          }
        }
        console.log(JSON.parse(JSON.stringify(data)))
        this.selectList = data
        this.automaticJump(this.selectList)
      },
      automaticJump(arr) {
        // console.log(arr)
        let jump = true
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].APP_SELECTS_VALUE.length > 1) {
            jump = false
          }
        }
        if (jump) {
          this.toWms()
        }
      },
      async getSelectResource(item) {
        const { data } = await getSelectResource({
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 9999,
          APP_CODE: this.appCode,
          LANGUAGE_CODE: this.getLanguage,
          ...item,
        })
        return data
      },
      async toWms() {
        for (let index = 0; index < this.selectList.length; index++) {
          const element = this.selectList[index]
          if (!element[element.SELECT_CODE]) {
            this.$baseMessage(translateTitle('Base.apps.请') + element.SELECT_NAME, 'warning')
            return
          }
        }
        this.toBtnLoading = true
        let obj = {}
        for (let index = 0; index < this.selectList.length; index++) {
          const element = this.selectList[index]
          if (element[element.SELECT_CODE]) {
            obj[element.SELECT_CODE] = element[element.SELECT_CODE]
          }
        }

        try {
          const { data } = await getUserInfo({
            appId: this.item.ID,
            appCode: this.item.APP_CODE,
            language: this.getLanguage,
            datas: {
              ...obj,
              token_reset: 'Y',
            },
          })
          console.log('跳转app', obj)
          this.item = { ...this.item, ...obj }
          // console.log('data', data.token)
          this.toBtnLoading = false
          if (data.pass) {
            this.toIndex(this.item, data.token)
          } else {
            this.$baseMessage(data.message, 'warning')
          }
        } catch (e) {
          this.toBtnLoading = false
        }
      },
      toIndex(item, token = '') {
        console.log('item', item)
        this.$store.dispatch('user/setbusinessCode', item)
        // this.$store.dispatch('user/setOrgCode', item.ORG_ID)
        this.$store.dispatch('user/setAppCode', item.APP_CODE)
        this.$store.dispatch('user/setAppId', item.ID)
        this.$store.dispatch('user/toApp', {
          tk: token,
          ...item,
        })
      },
      async orgChang(item, i) {
        console.log(item, this.selectList, i)
        if (!this.selectList[i + 1]) return
        let obj = item.APP_SELECTS_VALUE.find((el) => el[item.SELECT_CODE] == this.selectList[i][this.selectList[i].SELECT_CODE])
        let data = await this.getSelectResource({ ...obj, NEXT_SORT: this.selectList[i + 1].SORT })
        this.selectList[i + 1] = data
      },
      whChang(id) {
        this.form.WAREHOUSE_ID = id
      },
      handleCommand() {
        this.$store.dispatch('user/logout')
      },
    },
  })
</script>

<style lang="scss" scoped>
  .apps-container {
    background-image: url(../assets/wms_images/bg.png);
    background-size: cover;
    background-attachment: fixed;
    overflow: auto;
  }
  .app-item {
    height: 173px;
    background: #ffffff;
    border: 1px solid #e7e9ee;
    border-radius: 10px;
    width: 40%;
    max-width: 620px;
    box-shadow: 0px 4px 18px 0px rgba(80, 116, 235, 0.08);
    margin-bottom: 20px;
    margin-left: 6%;
    .item-text {
      width: 50%;
      text-align: left;
      .inter-btn {
        width: 100px;
        height: 32px;
        border: 1px solid #5473e8;
        border-radius: 4px;
        color: #5473e8;
        &:hover {
          background-color: #5473e8;
          color: #fff;
        }
      }
    }
    .item-img {
      width: 30%;
    }
  }

  .layer-modal-body {
    .org-item {
      width: 160px;
      height: 36px;
      background: #f0f2f4;
      border-radius: 21px;
      text-align: center;
      line-height: 36px;
      color: #8590a6;
      cursor: pointer;
      &.active-item {
        color: #3270ff;
        opacity: 0.8;
        background: #ebf3ff;
      }
    }

    .expandBtn {
      width: 63px;
      height: 26px;
      border: 1px solid #9fa9bc;
      border-radius: 16px;
      text-align: center;
      line-height: 26px;
      cursor: pointer;
      margin-top: 4px;
    }

    :deep(.el-input) {
      .el-input-group__prepend {
        background: #fff;
        width: 100px;
        .el-input__inner {
          font-weight: 600;
        }
      }
      .el-input-group__append {
        background: #3270ff;
        .el-button {
          background: #3270ff;
          color: #fff;
        }
      }
    }
  }

  :deep(.vfm) .vfm__container .vfm__content .modal-drag {
    border: none;
  }

  .commitBtn {
    width: 120px;
    height: 35px;
    background: #3270ff;
    border-radius: 4px;
  }
</style>
